package com.ztf.call;

import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@WebServlet("/getStudent")
public class GetStudent extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        ObjectMapper mapper = new ObjectMapper();
        Map<String,String> map = new HashMap<>();

        Jedis jedis = new Jedis("localhost",6379);

        int end = Math.toIntExact(jedis.llen("name"));
        if (end ==0){
            //说明,还没有上传文件  0是失败 ,1是成功
            map.put("isSuccess","0");
            map.put("err","选择失败,请重新上传");
            return;
        }


        Random random = new Random();
        int i = random.nextInt(end);

        //被选中的人
        String name = jedis.lindex("name", i);
        //删除这个人
        jedis.lrem("name",1,name);
        //封装数据 返回给前端
        map.put("isSuccess","1");
        map.put("name",name);
        mapper.writeValue(response.getOutputStream(),map);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
